package com.miao.im.support.tester;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializer;
import com.fasterxml.jackson.databind.ser.impl.ObjectIdWriter;
import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Set;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/7/14 19:39
 * @Description:
 */
public class TestJsonSerializer  extends JsonSerializer<Object> {

    private Class<? extends IConverter> converter;

    private String filedName;

    public TestJsonSerializer(Class<? extends IConverter> converter,String filedName) {
        this.converter = converter;
        this.filedName =filedName;
    }

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeObject(o);
        IConverter iConverter = ReflectUtil.newInstance(converter);
        String convert = iConverter.convert(o);
        jsonGenerator.writeStringField(filedName+"Text",convert);
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        // 为mapper注册一个带有SerializerModifier的Factory
        mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new TestBeanJsonModifier()));
        TestConvertObj testConvertObj = new TestConvertObj();
        testConvertObj.setCommand(1);
        testConvertObj.setMi(BigDecimal.ONE);
        TestConvertObj testConvertObj1 = new TestConvertObj();
        testConvertObj1.setCommand(2);
        testConvertObj.setTest(CollectionUtil.newArrayList(testConvertObj1));
        System.out.println(mapper.writeValueAsString(testConvertObj));
    }
}
